// 工具函数
const utils = {
  setSendResult: (code = 200, msg = "", data = null) => {
    return {
      code,
      msg,
      data,
    };
  },

  // 多表关联插入数据
   batchInsertWithTransaction: async(connection, table1Data, table2Data)=>{
    try {
      // 开始事务
      await connection.beginTransaction();
   
      // 批量插入第一个表
      const insertQuery1 = 'INSERT INTO table1 (column1, column2) VALUES ?';
      await connection.query(insertQuery1, [table1Data.map(row => [row.column1, row.column2])]);
   
      // 批量插入第二个表
      const insertQuery2 = 'INSERT INTO table2 (columnA, columnB, foreignKeyId) VALUES ?';
      const values = table2Data.map(row => [row.columnA, row.columnB, row.foreignKeyId]);
      await connection.query(insertQuery2, [values]);
   
      // 提交事务
      await connection.commit();
    } catch (err) {
      // 有错误时回滚
      await connection.rollback();
      throw err;
    }
  
  }
};

module.exports = utils;
